#include "AbpaFileFormat.h"
#include "ProcessInfo.h"

namespace events{


const char * AbpaFileFormat::MAGIC_FILE_HEADER = "ABPA";
const AbpaFileFormat::uint32 AbpaFileFormat::CURRENT_VERSION = 0x01000001;  // [1 byte] Major; [3 bytes] Minor


AbpaFileFormat::AbpaFileFormat(DWORD startTime)
: _valid(true), _version(CURRENT_VERSION)
{
	// get current time
	SYSTEMTIME stime;
	::GetSystemTime(&stime);
	_stime = stime;

	// get current relative time
	_tcount = (startTime == 0) ? ::GetTickCount() : startTime;

	// get current process name
	platform::ProcessInfo::GetCurrentProcessExeName(_pname);
}


/*
 * Saves current values to a file
 */
void AbpaFileFormat::saveAbpaHeader(std::ostream &os) const {
	os.write(MAGIC_FILE_HEADER, static_cast<unsigned long>(strlen(MAGIC_FILE_HEADER)));
	os.write(reinterpret_cast<const char *>(&_version), sizeof(uint32));
	_stime.saveToStream(os);
	_tcount.saveToStream(os);
	_pname.saveToStream(os);
}


/*
 * Reads file header
 */
AbpaFileFormat::AbpaFileFormat(std::istream &is) 
: _valid(true)
{
	// verify the magic word
	char buf[16];
	memset(buf, 0, 16);
	is.read(buf, static_cast<unsigned long>(strlen(MAGIC_FILE_HEADER)));
	if (0 != strncmp(buf, MAGIC_FILE_HEADER, strlen(MAGIC_FILE_HEADER))) {
		_valid = false;
		return;
	}

	// read the version, and the rest of parameters
	is.read(reinterpret_cast<char*>(&_version), sizeof(uint32));
	_stime.readFromStream(is);
	_tcount.readFromStream(is);
	_pname.readFromStream(is);
}



}  // end namespace
